import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import { loginApi } from '/@/api/login/index';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roleid: '',
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getUserInfoByToken();
				this.userInfos = userInfos;
			}
		},
		// 根据token查询用户信息
		async getUserInfoByToken() {
			let res = await loginApi().getUserInfoByToken();
			const userInfos = res.datas
			Session.set('userInfo', userInfos);
			return userInfos
		},
	},
});
